/*************************************************************************
 * File Name:    Best_Time_to_Buy_and_Sell_Stock.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: Sun 03 Nov 2013 10:18:15 AM CST
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: Best Time to Buy and Sell Stock
 |
 | Say you have an array for which the ith element is the price 
 | of a given stock on day i.
 |
 | If you were only permitted to complete at most one transaction
 | (ie, buy one and sell one share of the stock), design an algorithm to
 | find the maximum profit.
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <iomanip>

using namespace std;

class Solution {
public:
    int maxProfit(vector<int> &prices)
    {
        if (prices.size() == 0) return 0;
        
        int ans = 0;
        int last_stock = prices[0];
        
        for (size_t i = 1; i < prices.size(); ++i) {
            if (prices[i] > last_stock) {
                ans = max(ans, prices[i] - last_stock);
            } else {
                last_stock = prices[i];
            }
        }
        return ans;
    }
};
